/******************************************************************************
 * @File name   :      FileUtil.java
 *
 * @Author      :      JIZHANGS
 *
 * @Date        :      Sep 1, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2015 Capgemini, Inc. All  Rights Reserved.
 * This software is published under the terms of the Capgemini Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * Sep 1, 2015 3:42:34 PM        JIZHANGS     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.card.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 *
 */
public class FileUtil {

    private static final Logger LOGGER = Logger.getLogger(FileUtil.class);

    private FileUtil() {
    }
    
    public static HttpServletResponse downloadZip(File file, HttpServletResponse response,HttpServletRequest request) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            //response.setContentType("application/octet-stream")
            // 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setContentType("application/x-download charset=UTF-8");
            if(request.getHeader("USER-AGENT").toUpperCase().contains("FIREFOX")){
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
            }else{
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            }
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            // ex.printStackTrace()
            LOGGER.error("downloadZip", ex);
        } finally {
            try {
                File f = new File(file.getPath());
                if(f.delete()){
                    LOGGER.info("删除临时文件成功！");
                }
            } catch (Exception e) {
                LOGGER.error("downloadZip", e);
                // e.printStackTrace()
            }
        }
        return response;
    }
    
    public static HttpServletResponse downloadZip(File file, HttpServletResponse response,HttpServletRequest request,
    		String oldCodeType, String codeType) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            //response.setContentType("application/octet-stream")
            // 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setContentType("application/x-download charset=" + oldCodeType);
            if(request.getHeader("USER-AGENT").toUpperCase().contains("FIREFOX")){
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(file.getName().getBytes(oldCodeType),codeType));
            }else{
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(file.getName(), codeType));
            }
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            // ex.printStackTrace()
            LOGGER.error("downloadZip", ex);
        } finally {
            try {
                File f = new File(file.getPath());
                if(f.delete()){
                    LOGGER.info("删除临时文件成功！");
                }
            } catch (Exception e) {
                LOGGER.error("downloadZip", e);
                // e.printStackTrace()
            }
        }
        return response;
    }
    
    public static HttpServletResponse downloadFile(File file, HttpServletResponse response,HttpServletRequest request) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            //response.setContentType("application/octet-stream")
            // 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setContentType("application/x-download charset=UTF-8");
            if(request.getHeader("USER-AGENT").toUpperCase().contains("FIREFOX")){
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
            }else{
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            }
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            // ex.printStackTrace()
            LOGGER.error("downloadZip", ex);
        } 
        return response;
    }

    public static HttpServletResponse downloadFile(File file, HttpServletResponse response,HttpServletRequest request,
    		String oldCodeType, String codeType) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            //response.setContentType("application/octet-stream")
            // 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setContentType("application/x-download charset=" + oldCodeType);
            if(request.getHeader("USER-AGENT").toUpperCase().contains("FIREFOX")){
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(file.getName().getBytes(oldCodeType),codeType));
            }else{
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(file.getName(), codeType));
            }
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            // ex.printStackTrace()
            LOGGER.error("downloadZip", ex);
        } finally {
            try {
                File f = new File(file.getPath());
                if(f.delete()){
                    LOGGER.info("删除临时文件成功！");
                }
            } catch (Exception e) {
                LOGGER.error("downloadZip", e);
                // e.printStackTrace()
            }
        }
        return response;
    }

    /**
     * 删除创建时的临时文件
     * 
     * @param List
     *            <File>;
     */
    public static void deleteFiles(List<File> files) {
        for (int i = 0; i < files.size(); i++) {
            File file = (File) files.get(i);
            if(file.delete()){
                LOGGER.info("删除临时文件成功！");
            }
        }
    }
}
